<template>
  <div class="tabs">
    <!--切换tab -->
    <div class="tabs-bar">
      <div
        :class="['tabs-tab',{'tabs-tab-active':it.name===currVal}]"
        v-for="(it,index) in navList"
        @click="handleChange(index)"
        :key="it.name"
      >{{it.label}}{{it.name}}</div>
    </div>
    <!--展示内容 -->
    <div class="tabs-content">
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  name: "Tabs",
  props: {
    value: [String, Number],
    required: true
  },
  data() {
    return {
      currVal: "",
      navList: []
    };
  },
  methods: {
    handleChange(index) {
      let nav = this.navList[index];
      let name = nav.name;
      this.currVal = name;
      /** 派发 login组件使用 v-model=value的执行 */
      this.$emit("input", name);
      this.$emit("on-click", name);
    },
    getTabs() {
      // this.$children =>引入的组件比如: pane组件item.$options.name ===> name: "pane"
      return this.$children.filter(item => {
        return item.$options.name === "pane";
      });
    },
    updateActive() {
      this.navList = [];
      this.getTabs().forEach((pane, index) => {
        this.navList.push({
          label: pane.label,
          name: pane.name || index
        });
        //若初始化name的值0时,执行下面方法
        if (!pane.name) pane.name = index;
        //确保this.currVal=''的情况
        if (index === 0) {
          if (!this.currVal) {
            this.currVal = pane.name || index;
          }
        }
      });
      this.updateStatus();
    },
    updateStatus() {
      /**
       * 初始化pane对象中的show均为true,然后更新选中展示pane内容区域,未选中隐藏pane内容区域
       */
      this.getTabs().forEach((pane, index) => {
        let show = pane.name === this.currVal;
        pane.show = show;
        return pane.show;
      });
    }
  },
  watch: {
    value: function(val) {
      this.currVal = val;
    },
    currVal: function() {
      //更新选中状态
      this.updateStatus();
    }
  }
};
</script>
<style lang="stylus" scoped>
.tabs {
  position: relative
  top: 0
  left: 0
}
.tabs-bar {
  width: 100%
  // height: 38px 高度不可固定,自适应tab的内容高度，height与line-height的区别
  line-height: 38px
  border-bottom: 1px solid #c3c3c3
}
.tabs-tab {
  display: inline-block
  background: #fff
  font-size: 12px
  margin-right: 40px
  position: relative
  cursor: pointer
  user-select: none
}
.tabs-tab:last-child {
  margin-right: 0
}
.tabs-tab-active {
  font-size: 14px
  color: #232f45
  transition: 0.3s
}
.tabs-tab-active:after {
  content: ''
  display: block
  height: 3px
  background: #2acdcf
  border-radius: 2px
  position: absolute
  bottom: -2px
  width: 100%
}
.tabs-content {
  padding: 8px 0
}
</style>